//
//  FCollectionSelector.swift
//  Alamofire
//
//  Created by zhu xietong on 2018/1/8.
//

import Foundation
import Eelay

public class FKitCell: FCollectionSelectorCell {
    let infoL = UILabel()
    override public func addLayoutRules() {
        contentView.eelay = [
            [infoL,[ee.X.Y]],
        ]
        _ = infoL.ui.font20.center
    }
    
    override public func mo_model_reload() {
        infoL.text = mo.model["name",""]
        if mo.model[FK.selected,FK.NO] == FK.YES{
            contentView.backgroundColor = UIColor.main_color
            _ = infoL.ui.cl_fff
        }
        else{
            contentView.backgroundColor = UIColor(shex:"#eee")
            _ = infoL.ui.cl_222
        }
    }
}

open class FCollectionSelectorCell: JoCollectionCell {
    
    open class var sectionInset:UIEdgeInsets{
        get{
            return UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        }
    }
    
    open class var miniSpace:(X:Float,Y:Float){
        get{
            return (10,10)
        }
    }
    
    open class var itemSize:CGSize{
        get{
            let num = 2
            let w = (Swidth - sectionInset.left - sectionInset.right - miniSpace.X.cg_floatValue * (num.cg_floatValue-1.0))/num.cg_floatValue
            return CGSize(width: w, height: w)
        }
    }
}

open class FCollectionSelector<Kit:FCollectionSelectorCell>: ColsController {
    
    open var selector:TP.selector{
        get{
            let sec:TP.selector = [
                "<section0>":Kit.self,
            ]
            return sec
        }
    }
    
    open var selectedIDs = ""
    {
        didSet{
            if selectedIDs.len < 1{
                selectedValues = [String]()
            }
            else{
                var values = [String]()
                if let list = selectedIDs.JsonArray{
                    list.list({ (v:String, i) in
                        values.append(v)
                    })
                }else{
                    values.append("\(selectedIDs)")
                }
                selectedValues = values
            }
        }
    }
    
    
    open var sections:TP.section{
        get{
            var list = [[String:Any]]()
            
            weak var wself = self
            options.list { (dict:NSMutableDictionary, i) in
                var one = dict.swift_dictionary
                one[FK.selected] = FK.NO
                if let ws = wself{
                    if ws.justSelected(one: dict)
                    {
                        one[FK.selected] = FK.YES
                    }
                }
                list.append(one)
            }
            
            let sec:TP.section = [
                list,
                ]
            return sec
        }
    }
    
    open var selectedValues = [String]()
    
    var __selectedValues:[String]{
        get{
            var __vs = [String]()
            __selectedItems.list { (dict:NSMutableDictionary, i) in
                __vs.append(dict["id",""])
            }
            self.selectedValues = __vs
            return __vs
        }
    }
    
    open var valueChangedBlock:([String]) ->Void = {
        _ in
    }
    
    func justSelected(one:NSMutableDictionary)->Bool {
        var valid = false
        let id = one["id",""]
        if selectedValues.contains(id){
            valid = true
        }
        return valid
    }
    
    open var options = NSMutableArray()
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        self.flow.sectionInset = Kit.sectionInset
        self.flow.itemSize = Kit.itemSize
        self.flow.minimumLineSpacing = Kit.miniSpace.X.cg_floatValue
        self.flow.minimumInteritemSpacing = Kit.miniSpace.Y.cg_floatValue
        
        //        print("--====dd|\(sections)===||\(Kit.itemSize)")
        collectionView.load(sections: sections, selector: selector)
        collectionView.backgroundColor = UIColor.table_bg_color
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "确定".loc, style: .plain, target: self, action: #selector(confirmAction))
    }
    
    @objc func confirmAction()
    {
        self.valueChangedBlock(__selectedValues)
        self.navigationController?.popViewController(animated: true)
    }
    
    open var selectedMode:TagSelectMode = .singleNoToggle
    var __items:NSMutableArray{
        get{
            return DataNode.path(node: "section0", collectionView.model, value: NSMutableArray())
        }
    }
    
    var __selectedItems:NSMutableArray{
        get{
            let s_items = NSMutableArray()
            let items = DataNode.path(node: "section0", collectionView.model, value: NSMutableArray())
            items.list { (dict:NSMutableDictionary, i) in
                if dict[FK.selected,FK.NO] == FK.YES
                {
                    s_items.add(dict)
                }
            }
            return s_items
        }
    }
    
    
    
    open override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let data = collectionView.cellData(at: indexPath) else {
            return
        }
        switch selectedMode {
        case .singleToggle:
            var v = data[FK.selected,FK.NO]
            if v == FK.YES
            {
                v = FK.NO
            }
            else
            {
                v = FK.YES
            }
            
            __items.list({ (dict:NSMutableDictionary, i) in
                dict[FK.selected] = FK.NO
            })
            data[FK.selected] = v
//            self.valueChangedBlock(__selectedValues)
            collectionView.reloadData()
        case .singleNoToggle:
            __items.list({ (dict:NSMutableDictionary, i) in
                dict[FK.selected] = FK.NO
            })
            data[FK.selected] = FK.YES
//            self.valueChangedBlock(__selectedValues)
            collectionView.reloadData()
        case .mutil(min: _, max: let max, minMark: _, maxMark: let maxMark):
            
            var v = data[FK.selected,FK.NO]
            var canSelected = true
            if __selectedItems.count >= max ?? 1{
                if v == FK.NO
                {
                    canSelected = false
                    maxMark.alert()
                }
            }
            
            if canSelected{
                if v == FK.YES
                {
                    v = FK.NO
                }
                else
                {
                    v = FK.YES
                }
                data[FK.selected] = v
//                self.valueChangedBlock(__selectedValues)
                collectionView.reloadData()
            }
        }
    }
    
    open override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return Kit.itemSize
    }
    
}

